package kr.hkit.powerjava.chapter18;

import javax.swing.JPanel;

import java.awt.BorderLayout;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;

public class Panel_JList extends JPanel implements ActionListener, ListSelectionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField textField;
	private JTextField tfSelected;
	private JButton btnAdd;
	private JList<String> list;

	/**
	 * Create the panel.
	 */
	public Panel_JList() {

		initialize();
	}
	private void initialize() {
		setLayout(new BorderLayout(0, 0));
		
		JPanel panel_Top = new JPanel();
		add(panel_Top, BorderLayout.NORTH);
		
		textField = new JTextField();
		panel_Top.add(textField);
		textField.setColumns(10);
		
		btnAdd = new JButton("추가");
		btnAdd.addActionListener(this);
		panel_Top.add(btnAdd);
		
		JPanel panel_Center = new JPanel();
		add(panel_Center, BorderLayout.CENTER);
		
		list = new JList<String>(); //리스트 
		list.setModel(new DefaultListModel<String>()); //내용을 동적으로 추가하기 위해선 이걸 써야함
		list.addListSelectionListener(this);
		//디폴트가 MULTIPLE_INTERVAL_SELECTION 이므로 변경할려면 아래처럼 
		list.setVisibleRowCount(8); //화면에 보여지는 행의 개수
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
		
		
		JScrollPane scrollPane = new JScrollPane(list); //스크롤패인 안에 리스트
		panel_Center.add(scrollPane);
		
		JPanel panel_Bottom = new JPanel();
		add(panel_Bottom, BorderLayout.SOUTH);
		
		JLabel lblNewLabel = new JLabel("선택된 항목");
		panel_Bottom.add(lblNewLabel);
		
		tfSelected = new JTextField();
		tfSelected.setEditable(false); //변경불가하게
		panel_Bottom.add(tfSelected);
		tfSelected.setColumns(10);
		
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == btnAdd) {
			actionPerformedBtnAdd(e);
		}
	}
	
	protected void actionPerformedBtnAdd(ActionEvent e) { //btnAdd 버튼을 선택했을때
		DefaultListModel<String> model = (DefaultListModel<String>) list.getModel();
		
		String value = textField.getText().trim();
		model.addElement(value); //리스트에 추가하는 과정 
		
		textField.setText("");
		textField.requestFocus();
	}
	
	public void valueChanged(ListSelectionEvent e) {
		if (e.getSource() == list) {
			valueChangedList(e);
		}
	}
	
	protected void valueChangedList(ListSelectionEvent e) {
		
		tfSelected.setText(list.getSelectedValue()); //현재 선택된 항목을 반환
		
	}
}
